package cn.zl.mapper;

import cn.hutool.core.collection.CollectionUtil;
import cn.yunbamboos.mybatis.annotation.CustomQuery;
import cn.yunbamboos.mybatis.annotation.CustomUpdate;
import cn.yunbamboos.mybatis.annotation.GenerateXML;
import cn.yunbamboos.mybatis.conditions.Conditions;
import cn.yunbamboos.mybatis.mapper.GenericMapper;
import cn.zl.model.DeviceChannel;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@GenerateXML
@Repository
public interface DeviceChannelMapper extends GenericMapper<DeviceChannel> {

    @CustomQuery(sql = "select count(1) from zl_device_channel where device_id = #{device_id}", resultType = Integer.class)
    int countByDeviceId(@Param("device_id") String deviceId);

    default List<DeviceChannel> queryAllChannelsByDeviceId(@Param("device_id") String deviceId) {
        return this.queryForList(Conditions.create("device_id", deviceId));
    }

    default void cleanChannelsByDeviceId(@Param("device_id") String deviceId) {
        this.deleteByPrimaryKeys(Conditions.create("device_id", deviceId));
    }

    default int batchInsert(List<DeviceChannel> channels) {
        if (CollectionUtil.isEmpty(channels)) {
            return 0;
        }
        int num = 0;
        for (DeviceChannel channel : channels) {
            num += this.insert(channel);
        }
        return num;
    }

    default int batchUpdate(List<DeviceChannel> channels) {
        if (CollectionUtil.isEmpty(channels)) {
            return 0;
        }
        int num = 0;
        for (DeviceChannel channel : channels) {
            num += this.update(channel);
        }
        return num;
    }

    default int batchDelete(List<DeviceChannel> channels) {
        if (CollectionUtil.isEmpty(channels)) {
            return 0;
        }
        int num = 0;
        for (DeviceChannel channel : channels) {
            num += this.deleteByPrimaryKey(channel.getChannelId());
        }
        return num;
    }

    default Optional<DeviceChannel> queryByDeviceIdAndChannelId(String deviceId, String channelId) {
        return this.queryForObject(Conditions.create("device_id", deviceId).add("channel_code", channelId));
    }

    @CustomUpdate(sql = "update `zl_device_channel` set `status` = #{status} where `device_id` = #{device_id}")
    void updateStatusByDeviceId(@Param("device_id") String deviceId, @Param("status") boolean status);

}
